import math

from django.db import models

# Create your models here.
from utils.Base_model import Base


class Paths(Base):
    title = models.CharField('路径名称', max_length=32)
    desc = models.CharField('简介', max_length=256)
    img = models.ImageField('途径图片', upload_to='paths', null=True)
    follow = models.IntegerField('加入人数', default=0)

    class Meta:
        db_table = 'tb_paths'

    def __str__(self):
        return self.title

    def count_course(self):
        # 计算课程总数
        count = 0
        for stage in self.stage_set.all():
            count += stage.courses.count()
        return count

    def count_length(self):
        # 计算课程总时间
        count = 0
        for stage in self.stage_set.all():
            for course in stage.courses.all():
                count += course.count_length()
        return math.ceil(count / 60 * 100) / 100


class Stage(Base):
    title = models.CharField('阶段名称', max_length=24)
    sequence = models.IntegerField('序号', default=1)
    path = models.ForeignKey(Paths, on_delete=models.CASCADE)
    courses = models.ManyToManyField('course.Course')

    class Meta:
        db_table = 'tb_stage'
        ordering = ['sequence']

    def __str__(self):
        return '%s-%s' % (self.path.title, self.title)

# 用户加入路径关系表
class UserPath(Base):
    user = models.ForeignKey('user.User', on_delete=models.CASCADE)
    path = models.ForeignKey(Paths, on_delete=models.CASCADE)

    class Meta:
        db_table = 'tb_user_path'
